package com.myfum.mobile.tetris.utils
{
	import com.myfum.mobile.tetris.events.P2PEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.GroupSpecifier;
	import flash.net.NetConnection;
	import flash.net.NetGroup;
	import flash.net.NetGroupSendMode;
	import flash.utils.ByteArray;
	
	import org.robotlegs.mvcs.Actor;
	
	public class P2PHelper extends Actor
	{
		private var connection:NetConnection;
		
		private var group:NetGroup;
		
		private var _networkInfoText:String;
		
		public function P2PHelper()
		{
			
		}
		
		public function sendMessage(message:Object):void
		{
			var b:ByteArray = new ByteArray();
			b.writeObject(message);
			b.compress();
			group.sendToAllNeighbors(b);
		}
		
		public function connect():void
		{
			if(connection == null){
				connection = new NetConnection();
				connection.addEventListener(NetStatusEvent.NET_STATUS, handleNetConnectionStatus);
				connection.connect("rtmfp:");
			}
		}
		
		public function get networkInfoText():String
		{
			return _networkInfoText;
		}
		
		public function set networkInfoText(value:String):void
		{
			_networkInfoText = value;
			dispatch(new P2PEvent(P2PEvent.NET_STATES_CHANGED, networkInfoText));
		}
		
		private function handleNetConnectionStatus(event:NetStatusEvent):void
		{			
			networkInfoText = event.info.code;
			
			switch(event.info.code)
			{
				case "NetConnection.Connect.Success":
					setupGroup();
					break;
			}
		}
		
		private function handleNetGroupStatus(event:NetStatusEvent):void
		{			
			networkInfoText = event.info.code;
			
			switch(event.info.code)
			{
				case "NetGroup.Connect.Success":
					break;
				case "NetGroup.SendTo.Notify":
					var e:P2PEvent = new P2PEvent(P2PEvent.MESSAGE_RECIEVED, event.info);
					eventDispatcher.dispatchEvent(e);
					break;
			}
		}
		
		private function setupGroup():void
		{
			var groupSpec:GroupSpecifier = 
				new GroupSpecifier("localDeviceConnections");
			
			groupSpec.routingEnabled = true;
			groupSpec.ipMulticastMemberUpdatesEnabled = true;
			groupSpec.addIPMulticastAddress("224.255.0.0:35353");
			groupSpec.multicastEnabled = true;
			
			group = new NetGroup(connection, 
				groupSpec.groupspecWithAuthorizations());
			
			group.addEventListener(NetStatusEvent.NET_STATUS, 
				handleNetGroupStatus);
		}
	}
}